<template>
  <div>
    <!--搜索栏-->
    <el-form label-width="68px" :inline="true">
      <el-form-item label="用户名" prop="name" style="float: left">
        <el-input v-model="queryParams.username" placeholder="请输入用户名" clearable size="small"/>
      </el-form-item>
      <el-form-item label="性别" prop="sex" style="float: left">
        <el-select v-model="queryParams.sex" placeholder="请选择性别" clearable size="small">
          <el-option label="男" value="1" />
          <el-option label="女" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="state" style="float: left">
        <el-select v-model="queryParams.state" placeholder="请选择状态" clearable size="small">
          <el-option label="禁用" value="0" />
          <el-option label="启用" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item style="float: left">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="getUserList">搜索</el-button>
      </el-form-item>
    </el-form>
    <!--列表-->
    <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" fixed width="55" />
      <el-table-column prop="id" v-if="false" label="ID" width="120" />
      <el-table-column prop="username" fixed label="用户名" width="120" />
      <el-table-column prop="avatar" label="头像" width="150">
        <template slot-scope="scope">
          <img width="100" height="100" :src="scope.row.avatar"/>
        </template>
      </el-table-column>
      <el-table-column prop="birthday" :formatter="dateFormat" label="生日" width="150" />
      <el-table-column prop="sex" label="性别" width="150">
        <template slot-scope="scope">
          <span v-if="scope.row.sex == 1">男</span>
          <span v-else-if="scope.row.sex == 2">女</span>
        </template>
      </el-table-column>
      <el-table-column prop="email" label="邮箱" width="170" />
      <el-table-column prop="phone" label="手机号码" width="150" />
      <el-table-column prop="state" label="状态" width="150">
        <template slot-scope="scope">
          <el-switch class="switch"
                     :active-value="1" :inactive-value="0"
                     active-text="启用" inactive-text="禁用"
                     active-color="#1890ff" inactive-color="red"
                     v-model= scope.row.state @change="handleStatusChange(scope.$index, scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="150">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--分页-->
    <el-pagination
      @size-change="handleSizeChange" @current-change="handleCurrentChange"
      :current-page="queryParams.pageNum" :page-sizes="[5,10,20,40]"
      :page-size="queryParams.pageSize" layout="total, sizes, prev, pager, next"
      :total="total">
    </el-pagination>
    <!--修改对话框-->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="userForm" :rules="userRules" label-width="120px" style="height:350px">
        <div style="float: left; width: 50%" >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="userForm.username" placeholder="请输入用户名" />
          </el-form-item>
          <el-form-item label="头像" prop="avatar">
            <el-upload
              :class="{ uploadSty: showBtnImg, disUploadSty: noneBtnImg }"
              :ref="imageUpload"
              action="#"
              accept="image/png,image/gif,image/jpg,image/jpeg"
              list-type="picture-card"
              :limit="imageUpload.limitNum"
              :auto-upload="false"
              :before-upload="handleBeforeUpload"
              :on-change="imgChange"
              :on-remove="handleImgRemove"
              :file-list="headImages">
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="生日" prop="birthday">
            <el-date-picker
              v-model="userForm.birthday" type="date" placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </div>
        <div style="float: left; width: 50%">
          <el-form-item label="真实姓名" prop="realname">
            <el-input v-model="userForm.realname" placeholder="请输入真实姓名" />
          </el-form-item>
          <el-form-item label="手机号码" prop="phone">
            <el-input v-model="userForm.phone" placeholder="请输入手机号码" />
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <el-radio v-model="userForm.sex" :label="0" >隐藏</el-radio>
            <el-radio v-model="userForm.sex" :label="1" >男</el-radio>
            <el-radio v-model="userForm.sex" :label="2" >女</el-radio>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="userForm.email" placeholder="请输入邮箱" />
          </el-form-item>
          <el-form-item label="状态" prop="state">
            <el-radio v-model="userForm.state" :label="1" >启用</el-radio>
            <el-radio v-model="userForm.state" :label="0" >禁用</el-radio>
          </el-form-item>
        </div>
        <div style="float:left ; width: 100%">
          <el-form-item label="个人简介" prop="personalProfile">
            <el-input type="textarea" v-model="userForm.personalProfile" placeholder="请输入个人简介" />
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('form')">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {listUser,updateUser,getUser,deleteUser,verifyUsername} from "@/api/system/user";
  export default {
    data() {
      return {
        // 用户列表
        userList: [],
        // 遮罩层
        loading: true,
        // 总条数
        total: 0,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 5,
          username: null,
          sex: null,
          state: null
        },
        // 对话框标题
        title: '',
        headImages:[],
        // 是否显示弹出层
        open: false,
        isUploadImg: true,
        showBtnImg: true,
        noneBtnImg: false,
        limitCountImg: 1,
        imageUpload: {
          uploadFiles:[],
          //上传限制
          limitNum: 1, //需要修改为隐藏添加图片的入口
          // 上传的地址
          // url: "http://localhost:9000/static/common/upload", // 上传的图片服务器地址
        },
        // 修改表单参数
        userForm: {},
        // 修改用户对话框规则
        userRules: {
          username: [
            { required: true,message: '请输入用户名',  trigger: 'blur' },
            { min: 2, max: 6, success: 'sss' , message: '长度在 2 ~ 6 个字符', trigger: 'blur' },
            {validator: 'checkExistOfUserName',message: '用户名已存在'},
          ],
          phone: [
            {message:'请输入手机号码', trigger: 'blur'},
            //格式需要正确
            {pattern: '^1[0-9]{10}$',message: '手机号格式错误'},
          ],
          email: [
            { message: '请输入邮箱地址', trigger: 'blur' },
            { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
          ]
        },
      }
    },
    watch:{
      open(newValue,oldValue){
        if(!newValue){
          this.headImages.pop();
          this.noneBtnImg=false;
        }
      }
    },
    created() {
      this.getUserList()
    },
    methods: {
      // 校验昵称是否存在
      checkExistOfUserName(username){
        verifyUsername(username).then( (response) => {
          console.log("response.data", response.data);
        })
      },
      // 多选
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      // 用户列表
      getUserList (){
        this.loading = true
        listUser(this.queryParams).then(res => {
          this.userList = res.data.rows
          this.total = res.data.total
          this.loading = false
        })
      },
      // 初始页pageNum、初始每页数据数pagesize和数据data
      handleSizeChange: function (size) {
        this.queryParams.pageSize =  size;
        this.getUserList(); // 数据发生改变重新申请数据
      },
      handleCurrentChange: function(pageNum){
        this.queryParams.pageNum = pageNum;
        this.getUserList(); // 数据发生改变重新申请数据
      },
      // 改变用户状态
      handleStatusChange(index, row) {
        updateUser(row).then(res =>{
          this.$message.success("修改成功")
          this.getUserList()
        })
      },
      // 时间转换
      dateFormat:function(row,column){
        let date = row[column.property];
        if (date == undefined) {
          return "";
        }
        let moment = require("moment");
        return moment(date).format("YYYY-MM-DD");
      },
      // 图片上传
      handleBeforeUpload(file) {
        if (!(file.type === "image/png" ||
          file.type === "image/gif" ||
          file.type === "image/jpg" ||
          file.type === "image/jpeg")
        ){
          this.$notify.warning({
            title: "警告",
            message: "请上传格式为image/png, image/gif, image/jpg, image/jpeg的图片",
          });
        }
        let size = file.size / 1024 / 1024 / 2;
        if (size > 2) {
          this.$notify.warning({
            title: "警告",
            message: "图片大小必须小于2M",
          });
        }
      },
      imgChange(file, fileList) {
        this.userForm.avatar = file.url
        this.noneBtnImg = fileList.length >= this.limitCountImg;
      },
      handleImgRemove(file, fileList) {
        this.noneBtnImg = fileList.length >= this.limitCountImg;
      },
      // 修改用户
      handleUpdate(row){
        this.reset()
        this.headImages=[];
        getUser(row.id).then( res => {
          this.userForm = res.data.data
          this.headImages.push({url:this.userForm.avatar})
        })
        this.noneBtnImg=true;
        this.open = true
        this.title = '修改用户'
      },
      // 删除用户
      handleDelete(row){
        this.$confirm('是否确认删除用户', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(function () {
            return deleteUser(row.id);
          })
          .then(() => {
            this.getUserList()
            this.$message.success("删除成功！！！")
          })
          .catch(() => {
            this.$message.error("删除失败！！！")
          });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.userForm = {
          id: null,
          username: null,
          password: null,
          avatar: null,
          birthday: null,
          phone: null,
          sex: 0,
          email: null,
          state: 1,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
        };
      },
      // 提交修改
      submitForm(form){
        this.$refs["form"].validate((valid) => {
          if(valid){
            if(this.userForm.id != null){
              verifyUsername(this.userForm.username).then((response) => {
                if(response.data.code == 200){
                  updateUser(this.userForm).then( res =>{
                    this.$message.success("修改成功！！")
                    this.open = false
                    this.getUserList()
                  })
                }
              })
            }
          }
        })
      }
    },
  }
</script>

<style>
  .el-table th>.cell {
    display: inline-block;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    position: relative;
    vertical-align: middle;
    padding-left: 14px;
    padding-right: 14px;
    width: 100%;
    text-align: center;
  }
  .el-table .cell {
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: normal;
    word-break: break-all;
    line-height: 23px;
    padding-right: 10px;
    text-align: center;
  }
  .el-pagination {
    white-space: nowrap;
    padding: 5px 0px;
    color: #303133;
    font-weight: 700;
    background-color: white;
    width: 100%;
    text-align: right;
  }
  .el-form-item--medium .el-form-item__label {
    line-height: 36px;
  }
  /* switch按钮样式 */
  .switch .el-switch__label {
    position: absolute;
    display: none;
    color: #fff !important;
  }
  /*打开时文字位置设置*/
  .switch .el-switch__label--right {
    z-index: 1;
  }
  /* 调整打开时文字的显示位子 */
  .switch .el-switch__label--right span{
    margin-right: 9px;
  }
  /*关闭时文字位置设置*/
  .switch .el-switch__label--left {
    z-index: 1;
  }
  /* 调整关闭时文字的显示位子 */
  .switch .el-switch__label--left span{
    margin-left: 9px;
  }
  /*显示文字*/
  .switch .el-switch__label.is-active {
    display: block;
  }
  /* 调整按钮的宽度 */
  .switch.el-switch .el-switch__core,
  .el-switch .el-switch__label {
    width: 70px !important;
    margin: 0;
  }
  .el-dialog:not(.is-fullscreen) {
    margin-top: 6vh !important;
  }
  .disUploadSty .el-upload--picture-card {
    display: none; /* 上传按钮隐藏 */
  }
</style>
